/**
 * Created by oschina on 2014/8/3.
 */
angular.module('tweetMapApp', []);

var Conf = {
    'host' : 'http://www.oschina.net',
    'auth_uri' : '/action/oauth2/authorize',
    'response_type' : 'code',
    'client_id' : '9offZrPebB75IH24dpFH',
    'redirect_uri' : 'http://localhost:8080/Oauth2Action'
};

var Api = (function(conf, $) {

    var api = {};

    var uri = {
        'user' : '/action/user',
        'login' : conf.auth_uri + '?response_type=' + conf.response_type
            + '&client_id=' + conf.client_id + '&redirect_uri='
            + encodeURIComponent(conf.redirect_uri),
        'tweet_pop' : '/action/tweet'
    };



    var getCookie = function(name, value) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    };

    var delCookie = function(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = getCookie(name);
        if (cval != null)
            document.cookie = name + "=" + cval + ";expires="
                + exp.toGMTString();
    };

    var ajax = function(url, callback, data, async) {
        return $.ajax({
            url : url,
            type : 'POST',
            dataType : 'json',
            async : typeof async === 'undefined' ? true : async,
            data : data,
            success : function(response) {
                if (response == null)
                    return;
                ajaxErrorHandler(response, callback);
            },
            error : callback
        }).responseText;
    };

    var ajaxErrorHandler = function(response, callback, onError) {
        var data = typeof response === "object" ? response : eval('('
            + response + ')');

        if (data == null) {
            location.reload();
            return;
        }

        if (data.status == 500) {
            alert('500 服务器内部错误');
            location.reload();
            return;
        }
        if (data.error) {
            if (onError) {
                return onError(data);
            }
            if (data.code == 0) {
                alert(data.error);
                return;
            } else if (data.code == 1) {
                delCookie('user');
                location.reload();
                return;
            }
        }
        callback && callback(data);
    };

    var getUserInfo = function(callback) {
        var user_id = getCookie('user');
        if(user_id){
            return ajax(uri.user, callback, {
                user_id : user_id
            });
        }else{
            alert("需要授权登陆oschina账号");
            return user_id;
        }

    };

    var doLogin = function() {
        location.href = conf.host + uri.login;
    };

    var checkLogin = function() {
        return getCookie('user') != null;
    };

    var doLogout = function() {
        delCookie('user');
        location.reload();
    };

    var do_poptweet = function(msg,callback){
        var user_id = getCookie('user');
        if(user_id){
            return ajax(uri.tweet_pop, callback, {
                user_id : user_id,
                tweet : msg
            });
        }
    }



    api.ajax = ajax;
    api.cookie = getCookie;
    api.rcookie = delCookie;

    api.user = getUserInfo;
    api.login = doLogin;
    api.logout = doLogout;
    api.logined = checkLogin;
    api.pop_tweet= do_poptweet;
    api.on_error = ajaxErrorHandler;

    return api;

})(Conf, jQuery);

$(function() {

    var $user_info = $('.user-info')

    // 查询 login user 信息
    Api.user(function(user) {
        if (!user) {
            Api.rcookie('user');
            return;
        }
        var login = $user_info.find('a.login');
        var logout = $user_info.find('a.logout');
        var tmplogin = $user_info.find('span.login');
        tmplogin.hide();
        login.attr('href', user.url).attr('target', '_blank').text(
                user.name + ' ');
        logout.show().removeAttr('disabled');
    });

});